﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Warehouse.Web.AppCode;

namespace Warehouse.Web.Inventory
{
    public partial class Init : BasePage
    {
        const string InitStockSerialNumber = "000000000";
        protected List<DataAccess.Product> mProducts = null;
        protected List<DataAccess.ProductSpecification> mProductSpecifications = null;
        protected List<DataAccess.IncomingDetail> mStorage = null;
        protected List<DataAccess.Warehouse> mHouses = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.btnSave.Visible = false;

                mHouses = new List<Warehouse.DataAccess.Warehouse>(DataAccess.Warehouse.GetWarehouses());
                this.ddlWareHouse.DataSource = mHouses;
                this.ddlWareHouse.DataBind();

                int houseId = 0;
                if (int.TryParse(Request.QueryString["HouseID"], out houseId))
                {
                    this.ddlWareHouse.SelectedIndex = mHouses.FindIndex(p => p.ID == houseId);
                    LoadData(houseId);
                }
            }
        }

        protected void btnView_Click(object sender, EventArgs e)
        {
            int houseId = int.Parse(this.ddlWareHouse.SelectedValue);
            LoadData(houseId);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            int houseId = (int)ViewState["HouseID"];
            var warehouse = DataAccess.Warehouse.GetWarehouse(houseId);
            if (warehouse != null)
            {
                List<DataAccess.IncomingDetail> details = new List<Warehouse.DataAccess.IncomingDetail>();
                foreach (string k in Request.Form.Keys)
                {
                    if (k.StartsWith("Specification_"))
                    {
                        try
                        {
                            int sId = int.Parse(k.Replace("Specification_", ""));
                            int count = int.Parse(Request.Form[k]);
                            if (count < 0)
                            {
                                RegisterClientMessage("数量不能为负数");
                                return;
                            }
                            details.Add(new Warehouse.DataAccess.IncomingDetail()
                            {
                                Count = count,
                                Amount = 0,
                                Price = 0,
                                ProductSpecificationID = sId
                            });
                        }
                        catch
                        {
                            RegisterClientMessage("请输入整数");
                            return;
                        }
                    }
                }
                var stock = DataAccess.PurchaseBill.GetOne(p => p.HouseID == warehouse.ID && p.SerialNumber == InitStockSerialNumber);
                if (stock == null)
                {
                    stock = new Warehouse.DataAccess.PurchaseBill()
                    {
                        ID = Guid.NewGuid(),
                        SerialNumber = InitStockSerialNumber,
                        HouseID = warehouse.ID,
                        CreateDate = DateTime.Now,
                        Creator = User.Identity.Name,
                        BillType = Warehouse.DataAccess.PurchaseBillType.Init,
                        BillStatus = Warehouse.DataAccess.PurchaseBillStatus.Default,
                        Comments = "Init",
                        PurchaseDate = DateTime.MinValue,
                    };
                    stock.Save();
                }
                List<DataAccess.IncomingDetail> detailList = new List<Warehouse.DataAccess.IncomingDetail>(DataAccess.IncomingDetail.GetDetails(stock.ID));
                using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
                {
                    foreach (var d in details)
                    {
                        var old = detailList.SingleOrDefault(p => p.ProductSpecificationID == d.ProductSpecificationID);
                        if (old != null)
                        {
                            d.ID = old.ID;
                            detailList.Remove(old);
                        }
                        d.StockID = stock.ID;
                        d.Save();
                    }
                    foreach (var d in detailList)
                    {
                        d.Delete();
                    }
                    scope.Complete();
                }
                LoadData(houseId);
            }
            else
            {
                LoadData(houseId);
            }
        }

        void LoadData(int houseId)
        {
            var warehouse = DataAccess.Warehouse.GetWarehouse(houseId);
            if (warehouse != null)
            {

                this.hdHouseID.Value = warehouse.ID.ToString();
                this.ViewState["HouseID"] = warehouse.ID;

                var stock = DataAccess.IncomingStock.GetStock(warehouse.ID, InitStockSerialNumber);

                mProducts = new List<Warehouse.DataAccess.Product>(DataAccess.Product.GetProducts());
                mProductSpecifications = new List<Warehouse.DataAccess.ProductSpecification>(DataAccess.ProductSpecification.GetProductSpecifications());
                mStorage = new List<Warehouse.DataAccess.IncomingDetail>(stock != null ? DataAccess.IncomingDetail.GetDetails(stock.ID) : new DataAccess.IncomingDetail[0]);

                this.rptCategories.DataSource = DataAccess.ProductCategory.GetProductCategories();
                this.rptCategories.DataBind();

                this.btnSave.Visible = true;
            }
            else
            {
                base.RegisterClientMessage("请选择仓库");

                this.btnSave.Visible = false;
            }
        }

        protected void rptCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item == null)
                return;
            DataAccess.ProductCategory category = e.Item.DataItem as DataAccess.ProductCategory;
            Repeater rptProducts = e.Item.FindControl("rptProducts") as Repeater;
            if (category != null && rptProducts != null)
            {
                List<DataWrapper> list = new List<DataWrapper>();

                foreach (var group in mProducts.Where(p => p.CategoryID == category.ID).GroupBy(arg => arg.SerialNumber).OrderBy(arg => arg.Key))
                {
                    int _ProductSpecificatoinCount = group.Sum(p => Math.Max(1, mProductSpecifications.Count(arg => arg.ProductID == p.ID)));
                    bool firstProduct = true;
                    foreach (var p in group)
                    {
                        DataAccess.ProductSpecification[] _Specifications = mProductSpecifications.Where(arg => arg.ProductID == p.ID).ToArray();
                        int _SpecificatoinCount = _Specifications.Length;
                        bool firstSpecification = true;
                        foreach (var s in _Specifications)
                        {
                            double storagecount = 0;
                            var storage = mStorage.SingleOrDefault(arg => arg.ProductSpecificationID == s.ID);
                            if (storage != null)
                            {
                                storagecount = storage.Count;
                            }
                            list.Add(new DataWrapper()
                            {
                                FirstProduct = firstProduct,
                                FirstSpecification = firstSpecification,
                                ProductSpecificatoinCount = _ProductSpecificatoinCount,
                                SpecificatoinCount = _SpecificatoinCount,
                                Product = p,
                                Specification = s,
                                Count = storagecount
                            });
                            firstSpecification = false;
                            firstProduct = false;
                        }
                        if (firstSpecification)//没有添加任何规格
                        {
                            list.Add(new DataWrapper()
                            {
                                FirstProduct = firstProduct,
                                FirstSpecification = firstSpecification,
                                ProductSpecificatoinCount = _ProductSpecificatoinCount,
                                SpecificatoinCount = _SpecificatoinCount,
                                Product = p,
                                Specification = DataAccess.ProductSpecification.Empty,
                                Count = 0
                            });
                        }
                        firstProduct = false;
                    }
                }
                rptProducts.DataSource = list;
                rptProducts.DataBind();
            }
        }


        class DataWrapper
        {
            public bool FirstProduct { get; set; }
            public bool FirstSpecification { get; set; }
            public int ProductSpecificatoinCount { get; set; }
            public int SpecificatoinCount { get; set; }
            public double Count { get; set; }
            public DataAccess.Product Product { get; set; }
            public DataAccess.ProductSpecification Specification { get; set; }
        }
    }
}
